

CROSS_COMPILE ?= riscv64-unknown-linux-gnu-
CC := $(CROSS_COMPILE)gcc
LD := $(CROSS_COMPILE)ld
OBJCOPY := $(CROSS_COMPILE)objcopy
OBJDUMP := $(CROSS_COMPILE)objdump

COPS += -save-temps=obj -g -O2 -Wall \
		-nostdlib -nostdinc -Iinclude -mcmodel=medany \
		-mabi=lp64 -march=rv64imafd -fno-PIE \
		-fomit-frame-pointer

BUILD_ROOT = build
BUILD_DIR = $(BUILD_ROOT)/obj
SRC_DIR = src

TARGET = xmodem_recv
all : clean $(TARGET).bin 

# Check if verbosity is ON for build process
CMD_PREFIX_DEFAULT := @
ifeq ($(V), 1)
    CMD_PREFIX :=
else
    CMD_PREFIX := $(CMD_PREFIX_DEFAULT)
endif

clean :
	rm -rf $(BUILD_ROOT)  $(TARGET).bin  *.map *.elf

$(BUILD_DIR)/%_c.o: $(SRC_DIR)/%.c
	$(CMD_PREFIX)mkdir -p $(BUILD_DIR); echo " CC   $@" ; $(CC) $(COPS) -c $< -o $@

$(BUILD_DIR)/%_s.o: $(SRC_DIR)/%.S
	$(CMD_PREFIX)mkdir -p $(BUILD_DIR); echo " AS   $@"; $(CC) $(COPS) -c $< -o $@

C_FILES = $(wildcard $(SRC_DIR)/*.c)
ASM_FILES = $(wildcard $(SRC_DIR)/*.S)
OBJ_FILES = $(C_FILES:$(SRC_DIR)/%.c=$(BUILD_DIR)/%_c.o)
OBJ_FILES += $(ASM_FILES:$(SRC_DIR)/%.S=$(BUILD_DIR)/%_s.o)

DEP_FILES = $(OBJ_FILES:%.o=%.d)
-include $(DEP_FILES)

$(TARGET).bin: $(SRC_DIR)/linker.ld $(OBJ_FILES)
	$(CMD_PREFIX)$(LD) -T $(SRC_DIR)/linker.ld -o $(BUILD_DIR)/$(TARGET).elf  $(OBJ_FILES) -Map $(TARGET).map; \
	echo " LD $(BUILD_DIR)/$(TARGET).elf"
	$(CMD_PREFIX)$(OBJCOPY) $(BUILD_DIR)/$(TARGET).elf -O binary $(TARGET).bin; echo " OBJCOPY $(TARGET).bin"
	$(CMD_PREFIX)cp $(BUILD_DIR)/$(TARGET).elf $(TARGET).elf
	$(CMD_PREFIX)$(OBJDUMP) -D -S $(TARGET).elf > $(TARGET).S
	cp $(TARGET).bin ~/tftpboot/


run:
	qemu-system-riscv64 -nographic  -machine virt -m 128M  -bios fw_jump.bin -kernel $(TARGET).elf
debug:
	qemu-system-riscv64 -nographic -machine virt -m 128M -bios fw_jump.bin  -kernel $(TARGET).elf -S -s

